package com.zy.config;

import com.zy.common.ApiResult;
import com.zy.exception.BizcException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @Author CarreyZhou
 * @Date: 2024/5/3 11:37
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ApiResult<String> handleException(RuntimeException e) {
        log.error("Exception occurred: ", e);
        return ApiResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),e.getMessage());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BizcException.class)
    @ResponseBody
    public ApiResult<String> handleBizcException(BizcException e) {
        log.error("BizcException occurred: ", e);
        return ApiResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException occurred: ", e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError allError : allErrors) {
            errorMsg.append(allError.getDefaultMessage()).append(";");
        }
        return ApiResult.error(HttpStatus.BAD_REQUEST.value(), errorMsg.toString());
    }
}
